package cn.wolfcode.shop.service.impl;

import cn.wolfcode.shop.domain.UserInfo;
import cn.wolfcode.shop.domain.UserLogin;
import cn.wolfcode.shop.exception.UserException;
import cn.wolfcode.shop.mapper.UserInfoMapper;
import cn.wolfcode.shop.mapper.UserLoginMapper;
import cn.wolfcode.shop.service.IUserLoginService;
import cn.wolfcode.shop.util.MD5;
import cn.wolfcode.shop.util.RedisConstants;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;

import java.text.MessageFormat;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Created by wolfcode on 2018/8/20.
 */
@Service@Transactional
public class UserLoginServiceImpl implements IUserLoginService {
    @Autowired
    private UserLoginMapper userLoginMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    public UserLogin register(String username, String password) {
        int count = userLoginMapper.queryCountByUsername(username);
        if(count>0){
            throw new UserException("用户名已经注册");
        }
        UserLogin userLogin = new UserLogin();
        userLogin.setUserName(username);
        userLogin.setPassword(MD5.encode(password));
        userLoginMapper.insert(userLogin);
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userLogin.getId());
        userInfo.setRegistTime(new Date());
        userInfoMapper.insert(userInfo);
        return userLogin;
    }

    public String login(String username, String password) {
        UserLogin userLogin = userLoginMapper.login(username,MD5.encode(password));
        if(userLogin==null){
            throw new UserException("账户密码有误.");
        }
        //创建token,并返回
        String token = createToken(userLogin);
        return token;
    }
    public String createToken(UserLogin userLogin){
        String token = UUID.randomUUID().toString();
        String userKey = MessageFormat.format(RedisConstants.USER_LOGIN_TOKEN,token);
        redisTemplate.opsForValue().set(userKey,userLogin);
        redisTemplate.expire(userKey,30, TimeUnit.DAYS);
        return token;
    }

    public void logout(String token) {
        String userKey = MessageFormat.format(RedisConstants.USER_LOGIN_TOKEN,token);
        redisTemplate.delete(userKey);

    }
}

